// src/api/modules/userRegister.ts
import http from "@/utils/http";
import type { UnwrapRef } from "vue";
import axios from "axios";

const userRegister = {
    // 注册新用户
    register: (userData: any, file?: File) => {
        const formData = new FormData();

        // 将 user 数据转换为 JSON 字符串并添加到 formData
        formData.append("user", JSON.stringify(userData)); // 直接使用 JSON 字符串

        // 如果有文件，则添加到 formData
        if (file) {
            formData.append("file", file);
        }

        // 使用 axios 发送请求，不手动设置 Content-Type
        return http.post(`/register/add`, formData).then(response => {
            console.log('Registration successful:', response.data);
            return response;
        }).catch(error => {
            console.error('Registration failed:', error.response?.data || error);
            throw error;
        });
    },
    // 检查用户名是否唯一
    checkUsernameUnique: (username: string) => {
        // 构造查询参数
        const params = new URLSearchParams();
        params.append('username', username);

        // 使用 GET 方法发送请求
        return http.get(`/register/checkUsername?${params.toString()}`).then(response => {
            return response.data;
        }).catch(error => {
            throw error;
        });
    },
    // 检查电话是否唯一
    checkPhoneUnique: (phone: string) => {
        const params = {
            contact: phone
        };
        return http.get("/register/checkContact", {contact: phone}).then(response => {
            return response.data;
        }).catch(error => {
            throw error;
        });
    },
    // 发送短信验证码
    sendSmsCode: (phoneNumber: string) => {
        const params = {
            phoneNumber: phoneNumber
        };
        // 在 URL 中添加查询参数
        const url = `/sms/send-sms-code?${new URLSearchParams(params).toString()}`;
        return http.post(url).then(response => {
            console.log('Send SMS code result:', response.data);
            return response.data;
        }).catch(error => {
            console.error('Send SMS code failed:', error.response?.data || error);
            throw error;
        });
    },
    // 验证短信验证码
    verifySmsCode: (phoneNumber: string, inputCode: string) => {
        const params = {
            phoneNumber: phoneNumber,
            inputCode: inputCode
        };
        console.log('Verify SMS code params:', params);
        // 在 URL 中添加查询参数
        const url = `/sms/verify-sms-code?${new URLSearchParams(params).toString()}`;
        return http.post(url).then(response => {
            console.log('Verify SMS code result:', response);
            return response;
        }).catch(error => {
            console.error('Verify SMS code failed:', error.response?.data || error);
            throw error;
        });
    },
};

export default userRegister;
